/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package java.enterprise.web_jpa_war.dao;

import enterprise.web_jpa_war.entity.Person;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;



/**
 *
 * @author iryna.masyuk
 */
public class UserDAO {

    @PersistenceUnit
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction utx;
    EntityManager em = null;

    public void createPerson(String id, String firstName, String lastName) throws RollbackException, HeuristicMixedException, HeuristicRollbackException {
        try {
            //Create a person instance out of it
            Person person = new Person(id, firstName, lastName);
            
            //begin a transaction
            utx.begin();
            //create an em.
            //Since the em is created inside a transaction, it is associsated with
            //the transaction
            em = emf.createEntityManager();
            //persist the person entity
            em.persist(person);
            //commit transaction which will trigger the em to
            //commit newly created entity into database
            utx.commit();
            
        }
        //java.util.List<Person> getAllPersonsList(){
        //}
        catch (NotSupportedException ex) {
            Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SystemException ex) {
            Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally {
            //close the em to release any resources held up by the persistebce provider
            if(em != null) {
                em.close();
            }
        }
    }


    //java.util.List<Person> getAllPersonsList(){


    //}

}
